<script setup lang="ts">
import { routes } from "@/router/routes";
import { useRouter } from "vue-router";
import { computed, ref } from "vue";
import { userLoginStore } from "@/store/userStore";
import checkAccess from "@/access/checkAccess";

const loginUserStore = userLoginStore();

loginUserStore.fetchLoginUser();
const router = useRouter();
// 菜单选中 路由跳转时，自动更新选中的菜单项
const selectedKeys = ref<string[]>(["/"]);
router.afterEach((to) => {
  selectedKeys.value = [to.path];
});
// 路由跳转
const doMenuClick = (key: string) => {
  router.push({
    path: key,
  });
};
//过滤不想展示的页面
//computed 函数作用就是当这个函数中得值发生了变化，那就会重新执行一次函数
const visibleRoutes = computed(() => {
  return routes.filter((item) => {
    if (item.meta?.hideInMenu) {
      return false;
    }
    if (checkAccess(loginUserStore.loginUser, item.meta?.accsee as string)) {
      return false;
    }
    return true;
  });
});
const doLoginout = () => {
  loginUserStore.LoginoutUser();
};
</script>

<template>
  <div class="GlobalHeader">
    <a-row align="center" :wrap="false">
      <a-col flex="auto">
        <a-menu
          mode="horizontal"
          :selected-keys="selectedKeys"
          @menu-item-click="doMenuClick"
        >
          <a-menu-item
            key="0"
            :style="{ padding: 0, marginRight: '38px' }"
            disabled
          >
            <div class="title-bar"></div>
            <img class="logo" src="../assets/logo.png" />
            <div class="title">答题平台</div>
          </a-menu-item>
          <a-menu-item v-for="item in visibleRoutes" :key="item.path">
            {{ item.name }}
          </a-menu-item>
        </a-menu>
      </a-col>
      <a-col flex="100px">
        <div v-if="loginUserStore.loginUser.id">
          {{ loginUserStore.loginUser.userName ?? "错误用户" }}
          <a-button type="primary" @click="doLoginout">退出登录</a-button>
        </div>
        <div v-else>
          <a-button type="primary" href="/user/login">登录</a-button>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<style scoped>
.GlobalHeader {
}

.title-bar {
  display: flex;
  align-items: center;
}

.title {
  margin-left: 16px;
  color: black;
}

.logo {
  height: 48px;
  margin: 0 0 0 20px;
}
</style>
